<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Visit\Action;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Call\Constants\ClientTypeCode;
use MoChat\App\Client\Contract\ClientContract;
use MoChat\App\Client\Model\Client;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 *
 * @Controller
 */
class VisitClientListExport extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var ClientContract
     */
    protected $clientService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     *
     * @RequestMapping(path="/dashboard/visit/clientListExport", methods="GET")
     */
    public function handle(): array
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        // 校验参数
        $params = $this->request->all();
        $orderBy = isset($params['orderBy']) ? json_decode($params['orderBy'], true) : [];
        $list = Db::table('work_employee as employee')
            ->when(isset($params['employeeId']) && is_numeric($params['employeeId']), function ($query) use ($params) {
                $query->where('employee.id', $params['employeeId']);
            })
            ->when(isset($params['deptId']) && !empty($params['deptId']), function ($query) use ($params) {
                $query->where('dept.id', '=' , $params['deptId']);
            })
            ->when(!empty($orderBy), function ($query) use ($orderBy) {
                foreach ($orderBy as $key => $item) {
                    $query->orderBy($key, str_replace('end', '', $item));
                }
            })
            ->leftJoin('work_department as dept', 'employee.main_department_id', '=', 'dept.id')
            ->join('client as client', 'client.work_employee_id', 'employee.id')
            ->leftJoin('call_record as record', 'client.id', '=', 'record.client_id')
            ->where('record.call_duration', '>', 0)
            ->where('record.call_type', '=', "out")
            ->groupBy(['employee.id'])
            ->select([
                'employee.id',
                'employee.name',
                'dept.name as deptName',
                Db::raw("COUNT(DISTINCT mc_client.id) as clientCount"),
                Db::raw("COUNT(DISTINCT mc_record.destination_number) as callCount"),
                Db::raw("TRUNCATE(COUNT(DISTINCT mc_record.destination_number)/COUNT(DISTINCT mc_client.id),4) as rate")
            ])->get();
        $list || $list = collect([]);
        $list = $list->toArray();
        if (!empty($list)) {
            foreach ($list as &$item) {
                $item->rate = $item->rate ? bcmul($item->rate, '100', 2) . '%' : "0%";
            }
            unset($item);
        }
        return  $this->processingToTal($list);
    }

    /**
     * 组装基础数据
     * @param $tags
     * @return array
     */
    private function processingToTal($tags): array
    {
        $url = '';
        if (!empty($tags)) {
            $newExcel = new Spreadsheet();  //创建一个新的excel文档
            $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
            $objSheet->setTitle('拜访统计');  //设置当前sheet的标题

            //设置宽度为true,不然太窄了
            $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);

            //设置第一栏的标题
            $objSheet->setCellValue('A1', '员工')
                ->setCellValue('B1', '部门')
                ->setCellValue('C1', '客户列表总数')
                ->setCellValue('D1', '有效拜访数（接通电话）')
                ->setCellValue('E1', '拜访率');
            //第二行起，每一行的值,setCellValueExplicit是用来导出文本格式的。
            //->setCellValueExplicit('C' . $k, $val['admin_password']PHPExcel_Cell_DataType::TYPE_STRING),可以用来导出数字不变格式
            foreach ($tags as $k => $tag) {
                $k = $k + 2;
                $objSheet->setCellValue('A' . $k, $tag->name)
                    ->setCellValue('B' . $k, $tag->deptName)
                    ->setCellValue('C' . $k, $tag->clientCount)
                    ->setCellValue('D' . $k, $tag->callCount)
                    ->setCellValue('E' . $k, $tag->rate);
            }
            $url = $this->downloadExcel($newExcel, '拜访统计', 'Xlsx');
        }
        return ['url' => $url];
    }

    //公共文件，用来传入xls并下载
    public function downloadExcel($newExcel, $filename, $format)
    {
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, $format);

//        $objWriter->save('php://output');
        //通过php保存在本地的时候需要用到
        $url = BASE_PATH . '/storage/upload/static' . '/拜访统计.xlsx';
        $objWriter->save($url);
        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        //If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        return 'http://manage-cop.sczrk.cn/api/static/拜访统计.xlsx';
    }

}

